﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

namespace ProjectMadaktariMVC.Models
{
    public class EpisodeDAO
    {
        private static MadaktariDataContext db = DBFactory.DB;


        //Query Methods

        /// <summary>
        /// Returns all Episodes in the system
        /// </summary>
        /// <returns></returns>
        public List<Episode> FindAllEpisodes()
        {
            return db.Episodes.ToList<Episode>();
        }

        /// <summary>
        /// Returns an Episode with a given id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Episode GetEpisode(int id)
        {
            return db.Episodes.Single<Episode>(d => d.episodeID == id);
        }

        //Insert/Delete Methods

        /// <summary>
        /// Adds an Episode to the system.  Save() needs to be called for this change to be persisted.
        /// </summary>
        /// <param name="episode"></param>
        public void Add(Episode episode)
        {
            db.Episodes.InsertOnSubmit(episode);
        }
        
        /// <summary>
        /// Deletes an Episode from the system.  Save() needs to be called for this change to be persisted.
        /// </summary>
        /// <param name="episode"></param>
        public void Delete(Episode episode)
        {
            db.Episodes.DeleteOnSubmit(episode);
        }

        //Save Method

        /// <summary>
        /// Save all changes in the model to the database
        /// </summary>
        public void Save()
        {
            db.SubmitChanges();
        }

        public bool EpisodeHasDiagnosis(int episodeId, int diagnosisId)
        {
            var count = db.EpisodeDiagnosisRelationships.Count(rel => rel.diagnosisID == diagnosisId && rel.episodeID == episodeId);
            if (count > 0)
                return true;
            return false;
        }

        public void RemoveEpisodeDiagnosisRelationship(EpisodeDiagnosisRelationship rel)
        {
            db.EpisodeDiagnosisRelationships.DeleteOnSubmit(rel);
        }
    }
}
